package com.example.menhoo.toollibrary.common.utils;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

/**
 * 摇一摇
 * Created by yanglei on 15/9/25.
 */
public abstract class ShakeUtil implements SensorEventListener {

    int ACCELERATE_VALUE =15;//越小越灵敏

    // 传感器管理器
    private SensorManager sensorManager;
    // 传感器
    private Sensor sensor;

    // 上下文
    private Context mContext;


    // 构造器
    public ShakeUtil(Context c) {
        // 获得监听对象
        mContext = c;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {

        //越小越灵敏
        if(FastClickUtils.isFastClick(500)){
            return;
        }
        float[] values = event.values;
        float x = values[0];
        float y = values[1];
        float z = values[2];

        if (x >= ACCELERATE_VALUE || x <= -ACCELERATE_VALUE || y >= ACCELERATE_VALUE || y <= -ACCELERATE_VALUE || z >= ACCELERATE_VALUE || z <= -ACCELERATE_VALUE) {
            onShake();
        }

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    // 开始
    public void start() {
        // 获得传感器管理器
        sensorManager = (SensorManager) mContext
                .getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager != null) {
            // 获得重力传感器
            sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        }
        // 注册
        if (sensor != null) {
            sensorManager.registerListener(this, sensor,
                    SensorManager.SENSOR_DELAY_GAME);
        }

    }

    // 停止检测
    public void stop() {
        sensorManager.unregisterListener(this);
    }

    public abstract void onShake();
}
